//
//  MCOrderDetailWaitSendViewController.swift
//  StoreManage
//
//  Created by MC on 2017/12/21.
//  Copyright © 2017年 MC. All rights reserved.
//

import UIKit

class MCOrderDetailWaitSendViewController: MCViewController {
    
    var orderSn = ""
    
    private var isExpress = false
    private var companyNo = ""
    private var companyName = ""
    private var logisticsNo = ""

    override func viewDidLoad() {
        super.viewDidLoad()
        
        baseSetting()
        
        initUI()
        
        sendNetworking()
    }
    
    // MARK: - System Delegate
    
    // MARK: - Custom Delegate
    
    // MARK: - Action
    
    
    @objc func scanLogisticsSnEvent() {
        let vc = MCScanViewController()
        vc.customDelegate = self
        MCPushToViewController(current: self, target: vc, isHiddenBottomBarWhenBack: true)
    }
    
    @objc func changeCompanyEvent() {
        let vc = MCLogisticsCompanyViewController()
        vc.delegate = self
        MCPushToViewController(current: self, target: vc, isHiddenBottomBarWhenBack: true)
    }

    
    @objc func saveEvent() {
        if companyName.count == 0 {
            MCHUD_text(message: "请选择物流公司", view: self.view, delay: 1.5)
            return
        }
        
        if logisticsNo.count == 0 {
            MCHUD_text(message: "请填写物流单号", view: self.view, delay: 1.5)
            return
        }
        
        let para = [
            "expressCode" : companyNo,
            "expressName" : companyName,
            "expressNo"   : "persist",
            "orderSn"     : self.orderSn,
            "storeId"     : 0
            ] as [String : Any]
        
        MCNetwork_post(url: JAVA_updateOrderInfoStatus, para: para as [String : AnyObject], vc: self,hudSuperView: self.view,isHiddenTabbar: true, success: { (response) in
            
            MCHUD_text(message: "发货成功", view: self.view, delay: 1.5)
            DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 1.5, execute: {
                self.navigationController?.popViewController(animated: true)
            });
            
            
        }, dislike: { (response) in }) { (error) in }
        
    }

    @objc func scanCredentialsEvent() {
        let vc = MCScanViewController()
        vc.customDelegate = self
        MCPushToViewController(current: self, target: vc, isHiddenBottomBarWhenBack: true)
    }

    @objc func confirmEvent() {
        
        
        MCAlterController_twoOptions(vc: self, message: "尚未收到凭证，请谨慎发货", confirm: {
            
            let para = [
                "expressNo"   : "persist",
                "orderSn"     : self.orderSn,
                "storeId"     : MCUserinfo_getStoreId()
                ] as [String : Any]
            
            MCNetwork_post(url: JAVA_updateOrderInfoStatus, para: para as [String : AnyObject], vc: self,hudSuperView: self.view,isHiddenTabbar: true, success: { (response) in

                MCHUD_text(message: "发货成功", view: self.view, delay: 1.5)
                DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 1.5, execute: {
                   self.navigationController?.popViewController(animated: true)
                });
                
                
            }, dislike: { (response) in }) { (error) in }
        }) { }
    }
    

    
    // MARK: - Network
    func sendNetworking() {
        let para = [
            "orderSn" : orderSn,
            ] as [String : Any]
        
        MCNetwork_post(url: JAVA_getPersonageCentreListVoDetail, para: para as [String : AnyObject], vc: self,hudSuperView: self.view,isHiddenTabbar: true, success: { (response) in
            let dataDict = response["data"] as! [String : AnyObject]
            
            
            let model = MCOrderListFatherModel()
            model.setValuesForKeys(dataDict)
            self.headSectionView.model = model
            self.footSectionView.model = model
            self.footerView.model = model
            
            
            let deliveryWay = dataDict["deliveryWay"] as! NSNumber
            

            
            
            
            switch deliveryWay {
            case 3: // 快递送
                self.bottomView.isOnlyOneButton = true
                self.bottomView.rightButton.setTitle("保存", for: UIControlState.normal)
                self.bottomView.rightButton.addTarget(self, action: #selector(self.saveEvent), for: UIControlEvents.touchUpInside)
                break
            default:
                self.bottomView.isOnlyOneButton = false
                self.bottomView.leftButton.setTitle("扫描收货凭证", for: UIControlState.normal)
                self.bottomView.rightButton.setTitle("直接确认发货", for: UIControlState.normal)
                self.bottomView.leftButton.addTarget(self, action: #selector(self.scanCredentialsEvent), for: UIControlEvents.touchUpInside)
                self.bottomView.rightButton.addTarget(self, action: #selector(self.confirmEvent), for: UIControlEvents.touchUpInside)
                
                break
            }

            
            switch deliveryWay {
            case 1:
                self.isExpress = false
            case 2:
 
                self.isExpress = false
            case 3:
                self.isExpress = true
            default:
                break
            }

            
            
            let listBaOrderDetailVo = dataDict["listBaOrderDetailVo"] as! NSArray
            // 商品
            for dict in listBaOrderDetailVo {
                let model = MCOrderListModel()
                model.setValuesForKeys(dict as! [String : Any])
                self.dataArrayM.add(model)
            }
            self.tableView.reloadData()
            
        }, dislike: { (response) in }) { (error) in }
    }
    
    // MARK: - Method
    func baseSetting() {
        self.title = "待发货订单详情"
        self.view.backgroundColor = UIColor.white
        
        MCNotification_addObserver(name: NSNotification.Name.UIKeyboardWillShow.rawValue, vc: self, selector: #selector(keyboardWillShow(_:)))
        
        MCNotification_addObserver(name: NSNotification.Name.UIKeyboardWillHide.rawValue, vc: self, selector: #selector(keyboardWillHide(_:)))

    }
    
    // 键盘显示
    @objc func keyboardWillShow(_ notification: Notification) {
        let userInfo = (notification as NSNotification).userInfo!

        //键盘尺寸
        let keyboardSize = (userInfo[UIKeyboardFrameEndUserInfoKey]
            as! NSValue).cgRectValue
        let contentInsets:UIEdgeInsets = UIEdgeInsetsMake(0, 0.0, (keyboardSize.height), 0.0);

        let duration = userInfo[UIKeyboardAnimationDurationUserInfoKey]
        
        
        UIView.animate(withDuration: duration as! TimeInterval) {
            //tableview的contentview的底部大小
            self.tableView.contentInset = contentInsets;
            self.tableView.scrollIndicatorInsets = contentInsets;
        }
    }
    
    // 键盘隐藏
    @objc func keyboardWillHide(_ notification: Notification) {
        //还原tableview的contentview大小
        let contentInsets:UIEdgeInsets = UIEdgeInsetsMake(0, 0.0, 0, 0.0);
        self.tableView.contentInset = contentInsets
        self.tableView.scrollIndicatorInsets = contentInsets
    }
    
    func initUI() {
        
        view.addSubview(tableView)
        tableView.snp.remakeConstraints { (make) ->Void in
            make.edges.equalTo(view).inset(UIEdgeInsetsMake(0, 0, 44, 0))
        }
        tableView.tableFooterView = footerView
        
        view.addSubview(bottomView)
        bottomView.snp.remakeConstraints { (make) ->Void in
            make.left.right.bottom.equalTo(view)
            make.height.equalTo(44)
        }
        
    }
    
    // MARK: - Setter & Getter
    lazy private var tableView: MCTableView = {
        let tableView = MCTableView.init(frame: CGRect.zero, style: UITableViewStyle.grouped)
        tableView.delegate = self
        tableView.dataSource = self
        tableView.backgroundColor = UIColor.MCGray_light
        tableView.keyboardDismissMode = UIScrollViewKeyboardDismissMode.onDrag
        return tableView
    }()
    
    lazy var dataArrayM: NSMutableArray = {
        let arrayM = NSMutableArray()
        return arrayM
    }()
    
    lazy var footerView: MCOrderDetailWaitSendFooterView = {
        let view = MCOrderDetailWaitSendFooterView()
        view.orderNoTextField.delegate = self
        view.orderNoTextField.returnKeyType = UIReturnKeyType.done
        view.scanButton.addTarget(self, action: #selector(scanLogisticsSnEvent), for: UIControlEvents.touchUpInside)
        view.companybutton.addTarget(self, action: #selector(changeCompanyEvent), for: UIControlEvents.touchUpInside)
        
        
        view.orderNoTextField.closure = { () -> Void in
            self.logisticsNo = view.orderNoTextField.text ?? ""
        }
        
        return view
    }()
    
    lazy var bottomView: MCOrderDetailBottomView = {
        let view = MCOrderDetailBottomView()
        return view
    }()
    
    lazy var headSectionView: MCOrderListSectionHeaderView = {
        let view = MCOrderListSectionHeaderView()
        return view
    }()
    
    lazy var footSectionView: MCOrderListSectionFooterView = {
        let view = MCOrderListSectionFooterView()
        return view
    }()
}

extension MCOrderDetailWaitSendViewController : UITableViewDelegate,UITableViewDataSource {
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 55
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        return headSectionView
    }
    
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return 45
    }
    
    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        return footSectionView
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.dataArrayM.count
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 100
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        let cell = MCOrderListCell.init(style: UITableViewCellStyle.value1, reuseIdentifier: "cell")
        
        cell.selectionStyle = UITableViewCellSelectionStyle.none
        cell.model = self.dataArrayM[indexPath.row] as! MCOrderListModel
        
        return cell
    }
}


extension MCOrderDetailWaitSendViewController : MCLogisticsCompanyViewControllerDelegate {
    func MCLogisticsCompanyViewController_selectedCompany(model: MCLogisticsCompanyModel) {
        companyNo = model.companyNo
        companyName = model.companyName
        footerView.companybutton.setTitle(companyName, for: UIControlState.normal)
    }
}

extension MCOrderDetailWaitSendViewController : MCScanViewControllerDelegate {
    func MCScanViewController_getResult(str: String) {
        self.logisticsNo = str
    }
}

extension MCOrderDetailWaitSendViewController : UITextFieldDelegate {
    func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        
        if isExpress {
            self.logisticsNo = textField.text!
            self.footerView.orderNoTextField.resignFirstResponder()
        } else {
            let para = [
                "expressNo"   : textField.text!,
                "orderSn"     : self.orderSn,
                "storeId"     : 0
                ] as [String : Any]
            
            MCNetwork_post(url: JAVA_updateOrderInfoStatus, para: para as [String : AnyObject], vc: self,hudSuperView: self.view,isHiddenTabbar: true, success: { (response) in
                
                MCHUD_text(message: "发货成功", view: self.view, delay: 1.5)
                DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 1.5, execute: {
                    self.navigationController?.popViewController(animated: true)
                });
                
            }, dislike: { (response) in }) { (error) in }
        }
        

        
        return true
    }
}

